[C] Read line from file without knowing the line length.

Posted by ryyst on Stack Overflow See other posts from Stack Overflow or by ryyst
Published on 2010-03-28T09:29:30Z Indexed on 2010/03/28 9:33 UTC
Read the original article Hit count: 160

Filed under:
|

Hi,

I want to read in a file line by line, without knowing the line length before. Here's what I got so far:

int ch = getc(file);
int length = 0;
char buffer[4095];

while (ch != '\n' && ch != EOF) {
    ch = getc(file);
    buffer[length] = ch;
    length++;
}

printf("Line length: %d characters.", length);

I can now figure out the line length, but only for lines that are shorter than 4095 characters. Is there a better way to do this (I already used fgets() but got told it wasn't the best way)?

--Ry

© Stack Overflow or respective owner

Related posts about c

    Related posts about file-io